package com.skymxc.wandroidtodo.page.login;

import android.app.Application;
import android.util.Log;

import androidx.annotation.NonNull;

import com.skymxc.wandroidtodo.R;
import com.skymxc.wandroidtodo.data.pref.PrefUtils;
import com.skymxc.wandroidtodo.entity.NetResponse;
import com.skymxc.wandroidtodo.entity.NetResponseException;
import com.skymxc.wandroidtodo.entity.UserInfo;
import com.skymxc.wandroidtodo.page.base.BasePresenter;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * <p>
 *
 * </p>
 *
 * @author 孟祥超
 * <p>
 * date: 2021/12/1  7:14 上午
 */
public class LoginPresenter extends BasePresenter<LoginContact.LoginView> implements LoginContact.ILoginPresenter {

    public LoginPresenter(Application application) {
        super(application);
    }

    private LoginModel loginModel = new LoginModel();


    @Override
    public void login(String userName, String password) {
        view.showProgress(application.getString(R.string.logining));

        loginModel.login(userName, password)
                .subscribe(new Observer<UserInfo>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //防止内存泄漏
                        compositeDisposable.add(d);
                    }

                    @Override
                    public void onNext(@NonNull UserInfo userInfo) {
                        //保存一下用户
                        PrefUtils.saveUserInfo(userInfo);
                        view.loginSuccess();
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        e.printStackTrace();
                        if (e instanceof NetResponseException) {
                            view.showError(((NetResponseException) e).getErrorMsg(), ((NetResponseException) e).getErrorCode());
                        } else {
                            //错误处理
                            view.showError(e.getMessage(),-1);
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
